#!/bin/bash
# install:
# /usr/bin/install kf.sh /usr/bin/kf

version=0.8

usage() {
    cat <<EOF
kf: Knowledge Find.是一个简单的知识点检索工具。
versoin ${version}

kf [option <param>] str
-d <dir>        指定搜索的路径。默认为/var/log
-s <suffix>     指定搜索的文件后缀
-f cmd          指定过滤器命令
-c conf         指定配置文件,默认/etc/kf/kf.conf
-D              开启debug
-i              install kf
-h              查看帮助
-v              查看版本
EOF
}

debug() {
    if [ $debug -eq 1 ]
    then
    set -x
    fi
}

_debug() {
    if [ $debug -eq 1 ]
    then
    set +x
    fi
}

install() {
    tee kf.conf <<EOF
data_dir=/mnt/d/git/linux:/mnt/d/git/game_design
#filter=grep cheat_sheet
EOF

    if [ ! -d /etc/kf ]
    then
        mkdir -p /etc/kf
    fi

    set -x
    cp kf.conf ${conf_file}
    /usr/bin/install kf.sh /usr/bin/kf
    set +x
}

paser_conf() {
    if [ ! -f ${conf_file} ]
    then
        echo "${conf_file} not existed."
        exit 1
    fi

    # base_dir
    base_dir=`grep -v '#' ${conf_file} | grep data_dir`
    is_blank=`echo ${base_dir} | wc -c`
    if [ ${is_blank} -eq 0 ]
    then
        echo "can't find base_dir config opt"
        exit 1
    fi
    base_dir=`echo ${base_dir} | awk -F'=' '{print $2}'`
    base_dir=(${base_dir//:/ })

    # echo ${base_dir[@]}

    # filter
    if [ "$filter" == "" ]
    then
        filter=`grep -v '#' ${conf_file} | grep filter`
        is_blank=`echo ${filter} | wc -c`
        if [ ! ${is_blank} -eq 0 ]
        then
            filter=`echo ${filter} | awk -F'=' '{print $2}'`
        fi
    fi


    # echo $filter
}

exec_find() {
    _dir=$1
    debug
    if [ ! $_dir == '' ]
    then
        echo "dir:==${_dir}=="
        if [ "$filter" = "" ]
        then
            find ${_dir} -type f -name "*.${suffix}" | xargs grep -n -H -A ${A} -B ${B} -i -E "${s}"
        else
            find ${_dir} -type f -name "*.${suffix}" | $filter | xargs grep -n -H -A ${A} -B ${B} -i -E "${s}"
        fi
    fi
    _debug
}

# define global var
conf_file=/etc/kf/kf.conf
base_dir=/var/log
custom_dir=
suffix=md
A=0
B=0
debug=0
filter=

# parse args
while getopts "d:s:hvA:B:Dif:c:" flag
do
    case $flag in
    d) custom_dir="$OPTARG";;
    s) suffix="$OPTARG";;
    A) A="$OPTARG";;
    B) B="$OPTARG";;
    f) filter="$OPTARG";;
    c) conf_file="$OPTARG";;
    h) usage; exit 0;;
    v) usage; exit 0;;
    D) debug=1;;
    i) install; exit 0;;

    *) echo; usage; exit 1;;
    esac
done

shift $(($OPTIND - 1))

if [ $# -lt 1 ]
then
    usage
    exit 1
fi

# call parse_conf
paser_conf


file_name="\*.${suffix}"

if [ $debug -eq 1 ]
then
set -x
echo $#
echo ${base_dir[@]}
echo $file_name
echo $custom_dir
echo $@
set +x

fi

s=$@ # 要搜索的内容，支持正则表达式

if [ ! $custom_dir == "" ]
then
    exec_find $custom_dir
    exit 0
fi

debug
for dir in ${base_dir[@]}
do
    exec_find $dir
done
_debug